package com.dahua.download;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.dahua.R;


public class DownLoadService extends Service {

	DownLoader downLoader;

	Notification notification;

	NotificationManager notificationManager;

	boolean isFirst = true;

	int size = 0;
	int completeSize = 0;
	int temp = 0;
	boolean isComplete = false;

	private  String url = "";
	
	private  String fileName = "";
	// SD卡目录
	private  String path = "";
	// 下载器的Map KEY是URL
	private Map<String, DownLoader> downLoaders = new HashMap<String, DownLoader>();
	// handler用来处理进度条
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == 1) {
				DownloadInfo info = (DownloadInfo) msg.obj;

				if (info != null) {

					if (isFirst) {
						size = info.getFileSize();
						completeSize = info.getCompleteSize();
						isFirst = false;
						downLoader.download();
					}

					if (size == 0) {
						return;
					}
					completeSize += msg.arg2;

					int length = completeSize * 100 / size;

					if (temp < length) {
						temp = length;
					} else {
						return;
					}

					Log.i("5555", "进度====" + length);

					// 更改文字
					notification.contentView.setTextViewText(R.id.noti_tv,
							length + "%");
					// 更改进度条
					notification.contentView.setProgressBar(R.id.noti_pd, size,
							completeSize, false);
					// 发送消息
					notificationManager.notify(1, notification);

					if (size == completeSize || length == 100) {
						notification.contentView.setTextViewText(
								R.id.noti_status, "下载完成");
						notificationManager.notify(1, notification);
//						Toast.makeText(DownLoadService.this, "下载完成", 0).show();
						// 在数据库中把对应这个任务的下载信息删除
						downLoaders.get(url).deleteInfo(url);
						// 把这个任务的下载器移除
						DownLoader loader = downLoaders.remove(url);
						loader.closeDB();
						isComplete = true;
						Intent intent = new Intent("complete");
						sendBroadcast(intent);
						stopSelf();
						notificationManager.cancel(1);
					}

				}

			}
			if (msg.what==2) {
//				Toast.makeText(DownLoadService.this, "下载失败！", Toast.LENGTH_SHORT).show();
				stopSelf();
			}
			if (msg.what==3) {
//				Toast.makeText(DownLoadService.this, "下载失败！", Toast.LENGTH_SHORT).show();
//				DownLoader downLoader = downLoaders.get(url);
//				if (downLoader!=null) {
//					// 在数据库中把对应这个任务的下载信息删除
//					downLoaders.get(url).deleteInfo(url);
//				}
				// 把这个任务的下载器移除
				DownLoader loader = downLoaders.remove(url);
				if (loader!=null) {
					loader.closeDB();
				}
				stopSelf();
				if (notificationManager!=null) {
					notificationManager.cancel(1);
				}
				
			}

		}

	};

	/**
	 * 定义一个广播
	 */
	private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals("complete")) {
				installAPK(
						DownLoadService.this,
						Uri.fromFile(new File(path
								+ fileName)));
			}
			if (action.equals("stop")) {
				if (isComplete) {
					installAPK(
							DownLoadService.this,
							Uri.fromFile(new File(path
									+ fileName)));
					return;
				}
				if (downLoaders.get(url).state == 2) {
					pauseDownload();
					notification.contentView.setTextViewText(R.id.noti_status,
							"已暂停");
					notificationManager.notify(1, notification);
				} else if (downLoaders.get(url).state == 3) {
					isFirst = true;
					startDownload();
					notification.contentView.setTextViewText(R.id.noti_status,
							"下载中");
					notificationManager.notify(1, notification);
				}

			}
		}

	};

	/**
	 * 安装应用
	 * 
	 * @param context
	 * @param uri
	 */
	private void installAPK(Context context, Uri uri) {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(uri, "application/vnd.android.package-archive");
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		context.startActivity(intent);
	}

	/**
	 * 注册一个广播
	 */
	public void registerBoradcastReceiver() {
		IntentFilter myIntentFilter = new IntentFilter();
		myIntentFilter.addAction("complete");
		myIntentFilter.addAction("stop");
		// 注册广播
		registerReceiver(mBroadcastReceiver, myIntentFilter);
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		// TODO Auto-generated method stub
		if (intent!=null) {
			url = intent.getStringExtra("url");
			path = intent.getStringExtra("path");
			fileName=url.substring(url.lastIndexOf("/")+1,url.length());
			registerBoradcastReceiver();
			init();
			startDownload();
		}
		return super.onStartCommand(intent, flags, startId);
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
	}

	/**
	 * 点击开始下载
	 * 
	 */
	public void startDownload() {
		// 得到Button所在的LinearLayout，利用他得到textview上的文件名
		String urlString = url;// 下载地址
		String localFile = path + fileName;// 保存的目录
		int threadCount = 3;// 启动三个线程开始下载

		downLoader = downLoaders.get(urlString);
		// 如果下载器是空的，表示第一次下载或者下载已完成
		if (downLoader == null) {
			Log.v("TAG", "startDownload------->downLoader==null");
			// 开始一次下载，初始化一个下载器
			downLoader = new DownLoader(urlString, localFile, threadCount,
					this, mHandler);
			// 把下载器和标识这个下载器的URL放进MAP
			downLoaders.put(urlString, downLoader);
		}
		// 如果是正在下载，点击下载按钮
		if (downLoader.isDownloading()) {
			return;
		}
		downLoader.getDownloadInfo();
	}

	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(mBroadcastReceiver); // 注销广播
		if (!downLoaders.isEmpty()) {
			Set<Entry<String, DownLoader>> set = downLoaders.entrySet();
			for (Entry<String, DownLoader> entry : set) {
				entry.getValue().closeDB();
			}
			downLoaders = null;
		}
	}

	/**
	 * 暂停下载
	 * 
	 */
	public void pauseDownload() {
		downLoaders.get(url).pause();
	}

	/**
	 * 
	 */
	@SuppressWarnings("deprecation")
	private void init() {
		notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
		notification = new Notification(R.mipmap.ic_launcher, "Update",
				System.currentTimeMillis());
		RemoteViews view = new RemoteViews(getPackageName(), R.layout.noti);
		notification.contentView = view;
		notification.contentView.setTextViewText(R.id.noti_title,
				fileName);
		notification.contentView.setTextViewText(R.id.noti_status, "下载中");

//		Intent intent = new Intent("stop");
//		PendingIntent contentIntent = PendingIntent.getBroadcast(this,
//				R.string.app_name, intent, PendingIntent.FLAG_UPDATE_CURRENT);

//		 PendingIntent contentIntent = PendingIntent.getActivity(this,
//		 R.string.app_name, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//		notification.contentView.setOnClickPendingIntent(R.id.noti_total,
//				contentIntent);

//		notification.contentIntent = contentIntent;
		notification.flags = Notification.FLAG_NO_CLEAR;
		// 更改文字
		notification.contentView.setTextViewText(R.id.noti_tv,
				"0%");
		// 更改进度条
		notification.contentView.setProgressBar(R.id.noti_pd, 0,
				100, false);
		// 发送消息
		notificationManager.notify(1, notification);
	}

}
